package panda.buffer;

import panda.file.Block;

public class BufferManager {
	private static final long MAX_TIME = 10000;

	private BasicBufferManager basicBufferManager;

	public BufferManager(int bufferNumber) {
		basicBufferManager = new BasicBufferManager(bufferNumber);
	}

	public synchronized Buffer pin(Block block) {
		long startTime = System.currentTimeMillis();
		Buffer buffer = basicBufferManager.pin(block);
		try {
			while ((buffer == null)
					&& (System.currentTimeMillis() - startTime < MAX_TIME)) {
				wait(MAX_TIME);
				buffer = basicBufferManager.pin(block);
				if (buffer == null)
					throw new Exception("Request time out");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public synchronized Buffer pinNew(String fileName, PageFormatter formatter)
			throws Exception {
		long startTime = System.currentTimeMillis();
		Buffer buffer = basicBufferManager.pinNew(fileName, formatter);
		while ((buffer == null)
				&& (System.currentTimeMillis() - startTime < MAX_TIME)) {
			wait(MAX_TIME);
			buffer = basicBufferManager.pinNew(fileName, formatter);
		}
		if (buffer == null)
			throw new Exception("Request time out");
		return buffer;
	}

	public synchronized void unpin(Buffer buffer) {
		basicBufferManager.unPin(buffer);
		if (!buffer.ispinned()) {
			notifyAll();
		}
	}

	public void allPageOut(int transactionNumber) {
		basicBufferManager.allPageOut(transactionNumber);
	}

	public void clear(String fileName){
		basicBufferManager.clear(fileName);
	}
	
	public int available() {
		return basicBufferManager.available();
	}
}